package com.isunland.managesystem.utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DefaultAsyncHttpClient;
import com.isunland.managesystem.common.MyApplication;
import com.isunland.managesystem.entity.SuccessMessage;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;
import org.apache.http.Header;

/**
 * 文件联网工具类,包括上传文件,下载文件
 *
 * @author wangyanan
 */
public class FileNetWorkUtil {
  private static final String TAG = FileNetWorkUtil.class.getSimpleName();
  private Context mContext;
  private Context mAppContext = MyApplication.getAppContext();
  private NotificationManager mNotificationManager;
  private Notification mNotification;
  private RemoteViews mRemoteViews;

  public FileNetWorkUtil(Context context) {
    mContext = context;
  }

  /**
   * 上传文件
   *
   * @param mFilePath 文件在本地的路径
   * @param url 上传的url
   * @param map 上传的参数
   * @param handler 上传回调接口.默认的处理是提示上传成功,上传失败.不需要特殊处理就传空.
   */
  public void upLoadFile(String mFilePath, String url, HashMap<String, String> map,
      AsyncHttpResponseHandler handler) {
    this.upLoadFile(mFilePath, url, map, null, null, handler, false);
  }

  /**
   * 上传文件
   *
   * @param mFilePath 文件在本地的路径
   * @param url 上传的url
   * @param curtabName 表名(服务端提供)
   * @param curId 数据id(服务端提供)
   * @param handler 上传回调接口.默认的处理是提示上传成功,上传失败.不需要特殊处理就传空.
   */
  public void upLoadFile(String mFilePath, String url, String curtabName, String curId,
      AsyncHttpResponseHandler handler) {
    this.upLoadFile(mFilePath, url, null, curtabName, curId, handler, false);
  }

  /**
   * 上传文件
   *
   * @param mFilePath 文件在本地的路径
   * @param url 上传的url
   * @param curtabName 表名(服务端提供)
   * @param curId 数据id(服务端提供)
   * @param handler 上传回调接口.默认的处理是提示上传成功,上传失败.不需要特殊处理就传空.
   */
  public void upLoadFile(String mFilePath, String url, String curtabName, String curId,
      AsyncHttpResponseHandler handler, boolean isNeedThumbNail) {
    this.upLoadFile(mFilePath, url, null, curtabName, curId, handler, isNeedThumbNail);
  }

  /**
   * 上传文件
   *
   * @param mFilePath 文件在本地的路径
   * @param url 上传的url
   * @param map 上传的参数
   * @param curtabName 表名(服务端提供)
   * @param handler 上传回调接口.默认的处理是提示上传成功,上传失败.不需要特殊处理就传空.
   * @param isNeedThumbnail 是否需要缩略图.
   */
  public void upLoadFile(String mFilePath, String url, HashMap<String, String> map,
      String curtabName, String curid, AsyncHttpResponseHandler handler, boolean isNeedThumbnail) {
    if (TextUtils.isEmpty(mFilePath)) {
      LogUtil.e("mFilePath is empty");
      return;
    }
    if (TextUtils.isEmpty(url)) {
      LogUtil.e("url is empty");
      return;
    }
    if (!MyUtils.isNetLink(mContext)) {
      Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show();
      return;
    }
    if (handler == null) {
      handler = new myUpLoadHandler();
    }
    RequestParams params2 = new RequestParams();
    if (map != null) {
      for (Entry<String, String> entry : map.entrySet()) {
        params2.put(entry.getKey(), entry.getValue());
      }
    }
    if (curtabName != null) {
      params2.put("curtabName", curtabName);
    }
    if (curid != null) {
      params2.put("curid", curid);
    }
    // 扩展方便针对图片格式,进行图片压缩

    if (isNeedThumbnail) {
      params2.put("p_type", "images");
      params2.put("p_action", "doCompressByByte");
      params2.put("p_imgWidth", "80");
      params2.put("p_imgHeight", "80");
    }
    try {
      params2.put("fileBlob", new File(mFilePath));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      Toast.makeText(mContext, R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      return;
    }
    //params2.put("fileBlob", myInputStream, name);
    //}
    LogUtil.i(TAG, "url=" + url);
    LogUtil.i(TAG, "params2=" + params2.toString());
    DefaultAsyncHttpClient.post(url, params2, handler);
  }

  /**
   * 上传文件
   *
   * @param mFilePath 文件在本地的路径
   * @param url 上传的url
   * @param map 上传的参数
   * @param cursubsystem 上传的参数;
   * @param curtabName 表名(服务端提供)
   * @param handler 上传回调接口.默认的处理是提示上传成功,上传失败.不需要特殊处理就传空.
   * @param isNeedThumbnail 是否需要缩略图.
   */
  public void upLoadFile(String mFilePath, String url, HashMap<String, String> map,
      String cursubsystem, String curtabName, String curid, AsyncHttpResponseHandler handler,
      boolean isNeedThumbnail) {
    if (TextUtils.isEmpty(mFilePath)) {
      LogUtil.e("mFilePath is empty");
      return;
    }
    if (TextUtils.isEmpty(url)) {
      LogUtil.e("url is empty");
      return;
    }
    if (!MyUtils.isNetLink(mContext)) {
      Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show();
      return;
    }
    if (handler == null) {
      handler = new myUpLoadHandler();
    }
    RequestParams params2 = new RequestParams();
    if (map == null) {
      params2.put("cursubsystem", cursubsystem);
      params2.put("curtabName", curtabName);
      params2.put("curid", curid);
    } else {

      for (Entry<String, String> entry : map.entrySet()) {
        params2.put(entry.getKey(), entry.getValue());

        // Print it
      }
    }
    // 扩展方便针对图片格式,进行图片压缩

    if (isNeedThumbnail) {
      params2.put("p_type", "images");
      params2.put("p_action", "doCompressByByte");
      params2.put("p_imgWidth", "80");
      params2.put("p_imgHeight", "80");
    }
    try {
      params2.put("fileBlob", new File(mFilePath));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      Toast.makeText(mContext, R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      return;
    }
    LogUtil.i(TAG, "url=" + url);
    LogUtil.i(TAG, "params2=" + params2.toString());
    DefaultAsyncHttpClient.post(url, params2, handler);
  }

  /**
   * 一条记录对应多个上传文件
   *
   * @param mFilePath 文件在本地的路径
   * @param url 上传的url
   * @param map 上传的参数
   * @param cursubsystem 上传的参数;
   * @param curtabName 表名(服务端提供)
   * @param handler 上传回调接口.默认的处理是提示上传成功,上传失败.不需要特殊处理就传空.
   * @param isNeedThumbnail 是否需要缩略图.
   * @param resourcePath 多个附件上传成功路径对应服务端的参数
   */
  public void upLoadFilePath(String mFilePath, String url, HashMap<String, String> map,
      String cursubsystem, String curtabName, String curid, AsyncHttpResponseHandler handler,
      boolean isNeedThumbnail, String resourcePath) {
    if (TextUtils.isEmpty(mFilePath)) {
      LogUtil.e("mFilePath is empty");
      return;
    }
    if (TextUtils.isEmpty(url)) {
      LogUtil.e("url is empty");
      return;
    }
    if (!MyUtils.isNetLink(mContext)) {
      Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show();
      return;
    }
    if (handler == null) {
      handler = new myUpLoadHandler();
    }
    RequestParams params2 = new RequestParams();
    if (map == null) {
      params2.put("cursubsystem", cursubsystem);
      params2.put("curtabName", curtabName);
      params2.put("curid", curid);
      params2.put("fieldName", resourcePath);//多个附件时对应路径
    } else {

      for (Entry<String, String> entry : map.entrySet()) {
        params2.put(entry.getKey(), entry.getValue());

        // Print it
      }
    }
    // 扩展方便针对图片格式,进行图片压缩

    if (isNeedThumbnail) {
      params2.put("p_type", "images");
      params2.put("p_action", "doCompressByByte");
      params2.put("p_imgWidth", "350");
      params2.put("p_imgHeight", "180");
    }
    InputStream myInputStream = null;
    try {
      myInputStream = new FileInputStream(mFilePath);
    } catch (FileNotFoundException e) {

      LogUtil.e(TAG, "errorLog", e);
      Toast.makeText(mContext, R.string.fileNotFound, Toast.LENGTH_SHORT).show();
    }
    if (myInputStream != null) {
      String name = mFilePath.substring(mFilePath.lastIndexOf("/"), mFilePath.length());
      params2.put("file", myInputStream, name);
    }
    DefaultAsyncHttpClient.post(url, params2, handler);
  }

  public void downLoadFile(String filePah, String fileName, FileAsyncHttpResponseHandler handler) {
    if (TextUtils.isEmpty(filePah) || TextUtils.isEmpty(fileName)) {
      return;
    }
    if (!MyUtils.isNetLink(mContext)) {
      Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show();
      return;
    }
    if (handler == null) {
      File fileLocal = new File(FileUtil.getFileDir(), fileName);

      handler = new myDownLoadHandler(fileLocal);
    }

    RequestParams params2 = new RequestParams();
    params2.put("selcurFile", filePah);
    params2.put("selcurFileName", fileName);
    LogUtil.i(TAG, "parmas=" + params2.toString());
    DefaultAsyncHttpClient.post(ApiConst.URL_DOWNLOAD_FILE, params2, handler);
  }

  @SuppressWarnings("deprecation") private class myUpLoadHandler extends AsyncHttpResponseHandler {
    @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) {
      SuccessMessage message;
      try {
        message = new Gson().fromJson(new String(response), SuccessMessage.class);
        String result = message.getResult();
        LogUtil.i(new String(response));
        if (SuccessMessage.SUCCESS.equals(result)) {

          Toast.makeText(mContext, R.string.fileUploadSuccess, Toast.LENGTH_SHORT).show();
        }
        if (SuccessMessage.FAILURE.equals(result)) {

          Toast.makeText(mContext, R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
        }
      } catch (Exception e) {
        LogUtil.e("fileUploadError", e);
        // Toast.makeText(mContext, R.string.wrong_data,
        // Toast.LENGTH_SHORT).show();
        Toast.makeText(mContext, R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      }

      LogUtil.i(TAG, "response=" + new String(response));
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
      // LogUtil.e(TAG, "statusecode=" + statusCode + ",errorResponse="
      // + new String(errorResponse), e);
      Toast.makeText(mContext, R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
    }

    @Override public void onRetry(int retryNo) {
      // called when request is retried
    }
  }

  @SuppressWarnings("deprecation") private class myDownLoadHandler
      extends FileAsyncHttpResponseHandler {
    long mProgressTime;
    private File mFileLocal;
    private int notificationID;

    myDownLoadHandler(File file) {
      super(file);
      this.mFileLocal = file;
      this.notificationID = Integer.parseInt(MyDateUtil.format(new Date(), "HHmmss"));
      // Auto-generated constructor stub
    }

    @Override public void onStart() {

      Toast.makeText(mContext, R.string.isDownLoading, Toast.LENGTH_SHORT).show();
      initNotifycation();
    }

    @Override public void onProgress(long bytesWritten, long totalSize) {
      if ((System.currentTimeMillis() - mProgressTime) > 2000) {
        mProgressTime = System.currentTimeMillis();
        notifyProgress(bytesWritten, totalSize);
      }
    }

    @Override public void onSuccess(int statusCode, Header[] headers, File response) {
      // 下载成功后打开文件。
      //FileUtil.openFile(mFileLocal, mContext);//与notify
      try {
        Toast.makeText(mContext, R.string.download_success, Toast.LENGTH_SHORT).show();
        Intent intent = FileUtil.getFileIntent(file);
        notifyOpenFile(intent);
        //if (isAdded()) {
        // 用户离开当前界面,fragment在detach状态下.startActivity()会报错.
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        mAppContext.startActivity(intent);
      } catch (Exception e) {
        e.printStackTrace();
        ToastUtil.show(MyStringUtil.connect(R.string.openFile, R.string.failure));
      }
      //}
    }

    @Override public void onFailure(int arg0, Header[] arg1, Throwable arg2, File arg3) {
      MyUtils.dismissDialog();
      Toast.makeText(mContext, R.string.download_failed, Toast.LENGTH_SHORT).show();
      //下载失败后删除文件.
      FileUtil.deleteFile(mFileLocal);
      LogUtil.i(TAG, "responseError=" + arg0 + arg2 + arg3);
    }

    private void initNotifycation() {
      mNotificationManager =
          (NotificationManager) mAppContext.getSystemService(Context.NOTIFICATION_SERVICE);
      mNotification = new Notification();
      //noinspection deprecation
      mNotification.icon = R.drawable.ic_launcher;// 设置通知消息的图标
      mNotification.tickerText = "正在下载。。。";// 设置通知消息的标题
    }

    private void notifyProgress(@SuppressWarnings("UnusedParameters") long bytesWritten,
        @SuppressWarnings("UnusedParameters") long totalSize) {
      //int progressPercentage = (int) ((bytesWritten * 100 / totalSize));
      //DecimalFormat format = new DecimalFormat("0.00");
      //String progress = format.format(progressPercentage);
      if (mRemoteViews == null) {

        mRemoteViews = new RemoteViews(mAppContext.getPackageName(), R.layout.down_notification);
      }
      mRemoteViews.setImageViewResource(R.id.IconIV, R.drawable.ic_file_blue_128);
      mRemoteViews.setTextViewText(R.id.progressTv, "下载中");
      mRemoteViews.setTextViewText(R.id.tv_title_remoteView, file.getName());
      //mRemoteViews.setProgressBar(R.id.progressBar, 100, progressPercentage, false);
      mNotification.contentView = mRemoteViews;
      mNotificationManager.notify(notificationID, mNotification);
    }

    private void notifyOpenFile(Intent intent) {

      RemoteViews remoteViews =
          new RemoteViews(mAppContext.getPackageName(), R.layout.down_notification);
      remoteViews.setImageViewResource(R.id.IconIV, R.drawable.ic_file_blue_128);
      remoteViews.setTextViewText(R.id.progressTv, "下载完成");
      remoteViews.setProgressBar(R.id.progressBar, 100, 100, false);
      mNotification.contentView = remoteViews;
      if (intent != null) {
        mNotification.contentIntent = PendingIntent.getActivity(mAppContext, 0, intent, 0);
      }
      mNotification.flags = Notification.FLAG_AUTO_CANCEL;
      mNotificationManager.notify(notificationID, mNotification);
      // notificationManager.cancel(notificationID);
    }
  }
}
